package com.ihrm.common.session;

import org.apache.shiro.web.servlet.ShiroHttpServletRequest;
import org.apache.shiro.web.session.mgt.DefaultWebSessionManager;
import org.apache.shiro.web.util.WebUtils;
import org.springframework.util.StringUtils;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import java.io.Serializable;

/**
 * @author 小伟
 * @version V1.0
 * @Package com.ihrm.common.session
 * @date 2020/12/21 17:11
 * @Copyright © 2020-2021 郑州恒星科技有限责任公司
 * 自定义session会话管理类
 */
public class CommonSessionManager extends DefaultWebSessionManager {
    @Override
    protected Serializable getSessionId(ServletRequest request, ServletResponse response) {
        //获取请求中携带的sessionId
        String id = WebUtils.toHttp(request).getHeader("Authorization");
        //如果为空则新建一个session
        if (!StringUtils.hasLength(id)) {
        return super.getSessionId(request, response);
        }else {
            id = id.replaceAll("Bearer ", "");
           //sessionId 获取方式 从请求头中获取
            request.setAttribute(ShiroHttpServletRequest.REFERENCED_SESSION_ID_SOURCE,
                    "header");
            //保存sessionId 到session管理器中
            request.setAttribute(ShiroHttpServletRequest.REFERENCED_SESSION_ID, id);
            //sessionId是否需要验证
            request.setAttribute(ShiroHttpServletRequest.REFERENCED_SESSION_ID_IS_VALID,
                    Boolean.TRUE);
            //返回sessionId；
            return id;
        }
    }
}
